 <template>
  <div class="index-box" ref="index">
          <div class="echartBox d-flex" ref="echartBox">
            <el-card class="box-card flex1" style="margin-right:10px">
              <div class="btn-box">
                  <el-select v-model="year" placeholder="请选择年份" size="small" style="width:100px" clearable @change="topLeftFn()">
                      <el-option v-for="item in yearList" :key="item.value" :label="item.label" :value="item.value"/>
                  </el-select>
                  <el-select v-model="month" placeholder="请选择月份" size="small" style="width:100px" clearable @change="topLeftFn()">
                      <el-option v-for="item in monthList" :key="item.value" :label="item.label" :value="item.value"/>
                  </el-select>
              </div>
              <div id="leftEchart" ref="leftEchart"></div>
            </el-card>
            <el-card class="box-card flex1" style="margin-left:10px">
              <div class="btn-box">
                <el-select v-model="integralYear" placeholder="请选择年份" size="small" style="width:100px" @change="topRightFn()">
                    <el-option v-for="item in yearList" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
               <!-- <el-select v-model="integralMonth" placeholder="请选择月份" size="small" style="width:100px" clearable @change="topRightFn()">
                    <el-option v-for="item in monthList" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select> -->

              </div>
              <div id="rightEchart" ref="rightEchart"></div>
            </el-card>
          </div>
          <div class="echartBox d-flex" ref="echartCenterBox">
            <el-card class="box-card flex1" style="margin-right:10px;margin-top:15px">
              <div class="btn-box">
                  <el-select v-model="integralNumberTime" placeholder="请选择年份" size="small" style="width:100px" @change="centerLeftFn()">
                      <el-option v-for="item in yearList" :key="item.value" :label="item.label" :value="item.value"/>
                  </el-select>
              </div>
              <div id="centerLeftEchart" ref="centerLeftEchart" v-loading="centerLeftEchartLoading"></div>
            </el-card>
            <el-card class="box-card flex1" style="margin-left:10px;margin-top:15px">
              <div class="btn-box">
                <el-select v-model="newUserTime" placeholder="请选择年份" size="small" style="width:100px" @change="centerRightFn()">
                    <el-option v-for="item in yearList" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>

              </div>
              <div id="centerRightEchart" ref="centerRightEchart"></div>
            </el-card>
          </div>

          <div class="search" ref="search" style="margin-top: 15px;">
           <el-form :inline="true" :model="searchForm" size="small" ref="searchForm" @submit.native.prevent
              class="demo-form-inline" id="searchBox">
              <el-form-item prop="fromId">
                <el-select filterable clearable v-model="searchForm.fromId" placeholder="积分类型">
                  <el-option :label="item.name" :value="item.id" v-for="item in integralTypeList"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="registerTime">
                <el-date-picker v-model="registerTime" type="daterange" align="right" unlink-panels range-separator="至"
                  start-placeholder="注册开始日期" end-placeholder="注册结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>
              <el-form-item prop="getTime">
                <el-date-picker v-model="getTime" type="daterange" align="right" unlink-panels range-separator="至"
                  start-placeholder="获得开始日期" end-placeholder="获得结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>

              <el-form-item class="clearfix">
                <el-button type="primary" @click="handleSearch()" icon="el-icon-search">搜索</el-button>
                <el-button icon="el-icon-refresh" size="small" @click="resetSearch">重置</el-button>

              </el-form-item>
              <div class="actionBtnRight" style="margin-left:auto">
                <el-button
                  type="primary"
                  icon="el-icon-download"
                  size="small"
                  :loading="btnLoading"
                   v-has="'statistics:integralStatistics:down'"
                  @click="handleExport"
                >导出</el-button>
              </div>
            </el-form>
          </div>
          <div class="table" ref="table">
            <el-table :data="dataList" style="width: 100%;"  border v-loading="loading" stripe>
              <el-table-column type="index" label="编号" align="center" width="70"/>
              <el-table-column prop="userName" label="用户名称" align="center"/>
               <el-table-column prop="telephone" label="手机号" align="center"/>
              <el-table-column prop="fromIdentity" label="积分描述" align="center"/>
              <el-table-column prop="referrerName" label="分享/推荐人" align="center"/>
              <el-table-column prop="referrerTelephone" label="推荐人手机号" align="center"/>
              <el-table-column prop="totalPoints" label="总积分" align="center"/>
              <el-table-column prop="accumulatePoints" label="本次积分" align="center"/>
              <el-table-column prop="exchangeNum" label="已兑仟豆数" align="center"/>
              <el-table-column prop="createDate" label="注册日期" align="center" />
              <el-table-column prop="getDate" label="积分获取日期" align="center"/>
            </el-table>
          </div>
          <div class="page" ref="page">
           <MyPagination
              :total="total"
              :page.sync="searchForm.pageNum"
              :limit.sync="searchForm.pageSize"
              @pagination="tableList"
            />
          </div>

  </div>
</template>

<script>
  import common from '@/api/api';
  import {
   pointsReportGetCouponSource,getNewUserPoints,getNewUserStatistics,getPointsDetailList,getPointsTotal,pointsDetailListExport,getPopulationDistribution
  } from '@/api/getData'
  import option from '../../common/option.js';

  export default {
    data() {
      return {
        loading: false,
        btnLoading:false,
        centerLeftEchartLoading:false,
        yearList:[{label:'2020年',value:'2020'},{label:'2021年',value:'2021'},{label:'2022年',value:'2022'},{label:'2023年',value:'2023'},{label:'2024年',value:'2024'},{label:'2025年',value:'2025'}],
        monthList:[{label:'1月',value:'01'},{label:'2月',value:'02'},{label:'3月',value:'03'},{label:'4月',value:'04'},{label:'5月',value:'05'},{label:'6月',value:'06'},{label:'7月',value:'07'},{label:'8月',value:'08'},{label:'9月',value:'09'},{label:'10月',value:'10'},{label:'11月',value:'11'},{label:'12月',value:'12'}],
        year:"",
        month:'',
        integralYear:'',
        integralMonth:'',
        integralNumberTime:'',
        newUserTime:'',
        integralTypeList:[],
        registerTime:[],
        getTime:[],
        searchForm: {
          fromId:'',
          pageNum: 1,
          pageSize: 20,
        },
        tableHeight:0,//table 高度
        statusRow:{},
        dataList:[],
        total: 0,
        topData:{},

        consumerVoucherSum:0
      }
    },
    computed: {
      pickerOptions: () => {
        return option.pickerOptions;
      }
    },
    mounted() {
      let date = new Date();
      let Year = date.getFullYear(); //获取完整的年份(4位)
      let Month = date.getMonth(); //获取当前月份(0-11,0代表1月)
      this.year = Year;
      this.integralYear = Year;
      this.newUserTime = Year;
      this.integralNumberTime = Year;
      if(Month<9){
        this.month = '0'+(Month+1);
        this.integralMonth  = '0'+(Month+1);
      }else{
        this.month = Month+1;
        this.integralMonth =  Month+1;
      }

      this.topLeftFn();
      this.topRightFn();
      this.centerLeftFn();
      this.centerRightFn();

      this.tableList();

      this.getCategoryDetails({categoryKey:'points_inc_config'}).then(res=>{
        this.integralTypeList = res.data;
      })
     // this.tableList();
      this.$nextTick(() => {
          this.tableHeight = this.$refs.index.offsetHeight - this.$refs.page.offsetHeight   - this.$refs.echartBox.offsetHeight - this.$refs.search.offsetHeight   - 100;
      })
    },
    methods: {
      handleSearch(){
        this.page = 1;
        this.tableList();
      },
      resetSearch(){
        this.registerTime = [];
        this.getTime = [];
        this.resetForm('searchForm');
        this.tableList();
      },
      async tableList() {
        try {
         let data = this.addDateRange(this.searchForm, this.registerTime, 'registrationStartDate', 'registrationEndDate');
         data = this.addDateRange(this.searchForm, this.getTime, 'getStartDate', 'getEndDate');
         this.loading = true;
         const result = await getPointsDetailList(data);
         if (result.code == 200) {
           this.total = result.total;
           this.dataList = result.rows;
         } else {
           this.$message.error(result.msg);
         }
         this.loading = false;
        } catch (err) {
          this.loading = false;
          console.log(err)
        }
      },
      centerLeftFn(){
        this.centerLeftEchartLoading = true;
        getPointsTotal({date:this.integralNumberTime}).then(result=>{
          if (result.code == 200) {
              let data = result.data;
              let gather = [];//所有类型的集合
              let typeLength = 0; //单个月份类型的长度

              let xAxisData = [];
              let series = [];
              for(let i=0;i<data.length;i++){
                for(let key in data[i]){
                    xAxisData.push(key);
                    typeLength = data[i][key].length;
                  for(let a=0;a<data[i][key].length;a++){
                     gather.push(data[i][key][a]);
                  }
                }
              }
              for(let i=0;i<gather.length;i++){
                if(i<typeLength){
                  series.push({
                    name: gather[i].type,
                    type: 'bar',
                    barWidth: '15%',
                    data: [gather[i].num]
                  })
                }else{
                  let index = i-typeLength*(parseInt(i/typeLength));
                  series[index].data.push(Number(gather[i].num))
                }
              }
              this.centerLeftEchartLoading = false;
              this.centerLeftDataInfo(xAxisData,series);
          } else {
            this.centerLeftEchartLoading = false;
            this.$message.error(result.msg);
          }
        })
      },
      centerLeftDataInfo(xAxisData,series){
        let myChart = this.$echarts.init(document.getElementById('centerLeftEchart'));
        myChart.setOption({
          title: {
            text: '积分数统计',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: xAxisData,
              axisTick: {
                alignWithLabel: true
              }
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: series
        });
      },
      centerRightFn(){
        getNewUserPoints({date:this.newUserTime}).then(result=>{
          if (result.code == 200) {
            let xData = [];
            let yData = [];
            for(let i = 0;i<result.data.length;i++){
              xData.push(result.data[i].dataDate);
              yData.push(result.data[i].userNum);
            }
            this.centerRightDataInfo(xData,yData)
          } else {
            this.$message.error(result.msg);
          }
        })
      },
      topLeftFn(){
        let date = '';
        if(this.year){
          date+=this.year;
          this.month && (date+='-'+this.month)
        }
        this.consumerVoucherSum = 0;
        pointsReportGetCouponSource({date:date}).then(result=>{
          if (result.code == 200) {
              let data = result.data;
              data.map(item=>{
                item.value = item.num;
                item.name = item.type;
                this.consumerVoucherSum += Number(item.num);
              })
              this.topLeftDataInfo(data);
          } else {
            this.$message.error(result.msg);
          }
        })
      },
      topRightFn(){
        // let date = '';
        // if(this.integralYear){
        //   date+=this.integralYear;
        //   this.integralMonth && (date+='-'+this.integralMonth)
        // }
        this.integralNumberTotal = 0;
        getPopulationDistribution({date:this.integralYear}).then(result=>{
          if (result.code == 200) {
           let data = result.data;
           data.map(item=>{
             item.value = item.num;
             item.name = item.type;
             this.integralNumberTotal += Number(item.num);
           })
            this.topRightDataInfo(data)
          } else {
            this.$message.error(result.msg);
          }
        })
      },
      topLeftDataInfo(data){
        let myChart = this.$echarts.init(document.getElementById('leftEchart'));
        let consumerVoucherSum = this.consumerVoucherSum;
        myChart.setOption({
          title: {
            text: '积分类型分布图',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
             formatter: function (params) {
               let proportion = (Number(params.data.value) / consumerVoucherSum * 100) .toFixed(2) +'%';
                  return (`<div class='hang'>
                <div>
                  <div>${params.data.name}总数:${params.data.num}</div>
                  <div>占比:${proportion}</div>
                </div>
               </div>`);
                },
          },
          legend: {
             top: 'bottom'
          },
          series: [
            {
              type: 'pie',
              radius: '50%',
              data: data,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        });
      },
      //右上角折线图渲染
      topRightDataInfo(data){
        let myChart = this.$echarts.init(document.getElementById('rightEchart'));
        let integralNumberTotal = this.integralNumberTotal;
        myChart.setOption({
          title: {
            text: '积分人数分布',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
             formatter: function (params) {
               let proportion = integralNumberTotal=='0'?'0%':((Number(params.data.value) / integralNumberTotal * 100) .toFixed(2) +'%');
                  return (`<div class='hang'>
                <div>
                  <div>${params.data.name}总数:${params.data.num}</div>
                  <div>占比:${proportion}</div>
                </div>
               </div>`);
                },
          },
          legend: {
             top: 'bottom'
          },
          series: [
            {
              type: 'pie',
              radius: '50%',
              data: data,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        });
      },
      //中间右边上角折线图渲染
      centerRightDataInfo(xData,yData){
        let myChart = this.$echarts.init(document.getElementById('centerRightEchart'));
        console.log(123123)
        myChart.setOption({
             title: {
               text: '新用户积分统计',
                x:'center',
                y:'top',
               textAlign:'center'
             },
             tooltip: {
               trigger: 'axis'
             },
             legend: {
               data: ['Email'],
               top: 'bottom',
             },
             grid: {
               left: '3%',
               right: '4%',
               bottom: '10%',
               containLabel: true
             },
             toolbox: {

             },
             xAxis: {
               type: 'category',
               boundaryGap: false,
               data: xData
             },
             yAxis: {
               type: 'value'
             },
             series: [
               {
                 name: '积分',
                 type: 'line',
                 stack: 'Total',
                 data: yData
               }
             ]
        });
      },
      playCharts(xData,yData) {
        // 基于准备好的dom，初始化echarts实例
        let myChart = this.$echarts.init(document.getElementById('rightEchart'));
        let title = (this.unit == '万元'?'云仓总收益(年)':'云仓总收益(月)')
        // 绘制图表
        myChart.setOption({
             title: {
               text: title,
                x:'center',
                y:'top',
               textAlign:'center'
             },
             tooltip: {
               trigger: 'axis'
             },
             legend: {
               data: ['Email'],
               top: 'bottom',
             },
             grid: {
               left: '3%',
               right: '4%',
               bottom: '10%',
               containLabel: true
             },
             toolbox: {

             },
             xAxis: {
               type: 'category',
               boundaryGap: false,
               data: xData
             },
             yAxis: {
               type: 'value'
             },
             series: [
               {
                 name: '总收益',
                 type: 'line',
                 stack: 'Total',
                 data: yData
               }
             ]
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.$modal.confirm('是否确认导出筛选数据项？').then(() => {
          this.btnLoading = true;
          let data = this.addDateRange(this.searchForm, this.registerTime, 'registrationStartDate', 'registrationEndDate');
          data = this.addDateRange(this.searchForm, this.getTime, 'getStartDate', 'getEndDate');
          return pointsDetailListExport(data);
        }).then(response => {
          console.log(response.msg)
          this.$download.name(response.msg);
          this.btnLoading = false;
        }).catch(() => {});
      }

    }
  }
</script>

<style scoped lang="scss">
  .index-box{
        overflow-y: scroll;
  }
  .box-card{
    position: relative;
    .btn-box{
      position:absolute;
      right:15px;
      top:15px;
      z-index: 100;
    }
  }
  #rightEchart,#leftEchart,#centerLeftEchart,#centerRightEchart{
    width:100%;
    height:320px;
    margin-bottom:15px;
  }
  .el-table .el-dropdown-link{
      cursor: pointer;
      color: #61997A;
      margin-left: 5px;
  }
    .leftDialog{
      height:540px;
      overflow-y: auto;
    }
    .activeVerticalBox .activeItem{
      color:#61997A;
      cursor: pointer;
      margin: 0px;
      text-align: center;
      height:20px;
      line-height: 20px;
    }
    .activeVerticalBox .el-dropdown{
      display: flex;
      justify-content: center;
      color:#61997A;
      cursor: pointer;
    }
    .activeCheckedBox{
      border-top: 1px solid #ddd;
      padding:10px;
      height:52px;
      .el-tag{
        margin-right:10px;
      }
    }
    .rateBox /deep/ .el-rate__icon{
      margin-right: 0px;
    }
    .rateBox>p{
      margin: 0px;
    }
    .rateBox>p> /deep/ .el-rate{
      height:25px;
      line-height:25px;
      display:flex;
    }
    .rateBox>p> /deep/ .el-rate .el-rate__item{
      display:flex;
      align-items: center;
    }
    .rateBox .rateText{
      width:60px;
    }
    .rateBox .content{
      display: flex;
    }
    .rateBox .el-tooltip{
      width: 100px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      display: inline-block;
    }
</style>
